<?php
/****
* 基本用户信息model, 此处并不区分个人和社团用户
* 仅在此使用UCenter的接口, 从而对上层隐藏UCenter的存在
****/
import('@.Common.UCAdapter');
class AccountModel extends Model{
    protected $tableName=   'account';
    static private $_CONST=array(
        'STATE_LOCKED'=> -10,        //冻结, 特殊关照对象
        'STATE_NEW'=>   0,
        'STATE_NORMAL'=> 10,
        
        //角色权限设置, 高lv向下继承低lv权限
        'ROLE_USER_BASIC'=> 0,      //普通注册用户, 拥有参与/发布活动的能力
        'ROLE_USER_PRO'=> 10,       //高级注册用户, 拥有？？
        'ROLE_GROUP'=> 20,          //社团用户
        'ROLE_ADMIN'=> 50,          //普通管理员, 拥有审核/冻结指定活动/用户的能力
        'ROLE_DARK'=> 100,          //Notice黑幕！
    );
    static public function C($name){
        return self::$_CONST[$name];
    }
    protected $_validate    =      array( 
        //array('id', 'require', "错误的ID", Model::MUST_VALIDATE,'', Model::MODEL_INSERT ),
        //array('name','require',"请输入用户名",Model::EXISTS_VAILIDATE ), 
        array('email','require',"请输入邮箱", Model::EXISTS_VAILIDATE, '', Model::MODEL_INSERT), 
        array('repassword','password',"两次输入的密码不同", Model::EXISTS_VAILIDATE, 'confirm' )
        ); 
    public function login($username, $password){
        $u= UCAdapter::get()->user_login($username, $password);
        if ($u[0] >0){
            $u['uid']= $u[0];
            $u['username']= $u[1];
            $u['email']= $u[3];
            //加载notice Account本身信息
            $un= $this->find($u[0]);
            if (! $un){
                //UC中的用户未在notice中注册, 则自动同步资料
                $un= array(
                    'uid'=> $u[0],
                    'name'=> $u['username'],
                    'email'=> $u['email'],
                    'role'=> self::C('ROLE_USER_BASIC'),
                    'state'=> self::C('STATE_NEW'),
                );
                $this->add($un);
            }
            $u+= $un;
        }
        return $u;
    }
    public function getByID($uid){
        //扩充ucenter中的内容
        $uc= UCAdapter::get()->get_user($uid, true);
        //兼容qsc_usercenter
        if (array_key_exists(0, $uc)) { 
            if ($uc[0] <=0){                                    
                $res= null;
                return $res;
            }
            $res= $this->find($uid);
            $res['username']= $uc[1];
        } else {
            if ($uc['uid'] <=0) {
                $res= null;
                return $res;
            }  
            $res= $this->find($uid);
            $res['username']= $uc['username'];
        }
        return $res;
    }
    public function deleteByID($uid){
        $AM= M('Account');
        //TODO
    }
    public function checkState($state){
        if (    self::C('STATE_LOCKED')==$state
            ||  self::C('STATE_NEW'   )==$state 
            ||  self::C('STATE_NORMAL')==$state ){
            return $state;
        } else{
            return null;
        }
    }
    public function checkRole($role){
        if (self::C('ROLE_USER_BASIC')==$role  ||
            self::C('ROLE_GROUP')==$role
            ){
            return $role;
        } else{
            return null;
        }
    }
    /****
    * 注册并向Passport传递信息
    */
    public function register($data='',$options=array()) {
        if(empty($data)) {
            // 没有传递数据, 获取当前数据对象的值
            if(!empty($this->data)) {
                $data    =   $this->data;
            }else{
                $this->error = L('_DATA_TYPE_INVALID_');
                return false;
            }
        }
        $data['uid']= UCAdapter::get()->user_register($data['username'] , $data['password'] , $data['email']);
        if ($data['uid'] <=0){
            switch($data['uid']){
            case -1:    $this->error="uc_用户名长度不和要求, 或包含非法字符"       ; break;
            case -2:    $this->error="uc_输入中含有[敏感词]";break;
            case -3:    $this->error="uc_用户名已经存在"     ;break;
            case -4:    $this->error="uc_Email 格式有误"     ; break;
            case -5:    $this->error="uc_该 Email 已被禁止注册"   ; break;  
            case -6:    $this->error="uc_该 Email 已经被注册"; break;    
            }
            return false;
        }
        if (self::C('ROLE_GROUP')!= $data['role']){
            $data['role']= self::C('ROLE_USER_BASIC');
        }
        
        $this->add($data, $options);
        return $data['uid'];
    }
    public function edit($uid, $data){
        if (!$data['username']){
            //TODO: 处理传递为uid而非username的情况
            return false;
        }
        $ignorePassword= true;
        if (array_key_exists('password', $data)) {
            //要求修改密码, 则需要原始密码
            $ignorePassword= false;
            if ($data['repassword']!== $data['repassword']){
                $this->error= "两次输入的密码不一致";
                return false;
            }
        }
        $res=0;
        if (array_key_exists('password', $data) || array_key_exists('email', $data)){
            $res= UCAdapter::get()->user_edit($data['username'], $data['oldpassword'], $data['password'], 
                                $data['email'], $ignorePassword);
        }
        if (1!=$res && 0!=$res){
                   if(-1 ==$res){    $this->error="旧密码不正确";
            } else if(-4 ==$res){    $this->error="Email 格式有误";
            } else if(-5 ==$res){    $this->error="Email 不允许注册";
            } else if(-6 ==$res){    $this->error="该 Email 已经被注册";
            } else if(-7 ==$res){    $this->error="没有做任何修改";
            } else if(-8 ==$res){    $this->error="该用户受保护无权限更改";
            }           
            return false;
        }
        $data['uid']= $uid;
        return $this->data($data)->save();
    }
    // 获取所有正向好友
    // 修正从UC获取的好友列表以便模板输出
    public function getFriends($uid, $limit=200) {
        $friends= UCAdapter::get()->friend_ls($uid, 1, $limit, $limit);
        foreach ($friends as &$f) {
            $f['uid']= $f['friendid'];
            $f['name']= $f['username'];
        }
        return $friends;
    }
    public function getRevFriends($uid, $limit=200) {
        $friends= UCAdapter::get()->friend_ls($uid, 1, $limit, $limit, 2);
        foreach ($friends as &$f) {
            //$f['uid']= $f['uid'];
            //由于原本UCenter的bug, username是本人名字...
            $f['name']= $f['username'];
        }
        return $friends;
    }
    /****
     * 判断指定id是否已经被添加为好友
     ****/
    public function hasFriend($uid, $friendids) {
        if (! is_array($friendids)) {
            $friendids= array($friendids);
        }
        //由于坑爹的UCenter, 无法直接判断
        $ret= UCAdapter::get()->friend_isfriend($uid, $friendids);
        return $ret;
    }
    protected function _before_insert(&$data,$options) {
        //回调._before_insert()时data已经被修正
    }
    protected function _after_update($data,$options) {
        //由于event表中存在role缓存, 在此同步
        //.setField()最后也会调用.save(), 但此时data不一定包含主键
        if (array_key_exists('role', $data)){
            $map=array('author_id'=> $options['where']['uid']);
            $em= M('event');
            $r= $em->where($map)->setField('role', $data['role']);
        }
    }
}
?>